//
//  UIControl+HCTB.m
//  HCToolBox
//
//  Created by Hotacool on 2019/4/19.
//

#import "UIControl+HCTB.h"
#import <objc/runtime.h>
#import "NSObject+HCTB.h"

@implementation UIControl (HCTB)

- (void)addActionBlock:(hcActionBlock)actionBlk forControlEvents:(UIControlEvents)controlEvents {
    if (actionBlk) {
        SEL sel = NSSelectorFromString([NSString stringWithFormat:@"hctb_actionForControlEvents%lu", (unsigned long)controlEvents]);
        NSString *key = [NSString stringWithFormat:@"hctb_blockForControlEvents%lu",(unsigned long)controlEvents];
        BOOL isAddedMethod = NO;
        if ([self respondsToSelector:sel]) {
            isAddedMethod = YES;
        } else {// lazy add method to class
            IMP imp = imp_implementationWithBlock(^(id sender) {
                hcActionBlock block = [sender hctb_objectForKey:key];
                if (block) {
                    block(sender);
                }
            });
            isAddedMethod = class_addMethod([self class], sel, imp, "v@:@");
        }
        [self hctb_setObject:actionBlk forKey:key];
        if (isAddedMethod) {// add target to instance
            [self addTarget:self action:sel forControlEvents:controlEvents];
        }
    }
}
@end
